package leetcode_1901_2000;

import java.util.*;

public class LeeCode_1942 {
    public static void main(String[] args) {
        System.out.println(smallestChair(new int[][]{{1, 4}, {2, 3}, {4, 6}}, 1));
    }
    private static int smallestChair(int[][] times, int targetFriend) {
        int n = times.length;
        int arrive = times[targetFriend][0];
        TreeMap<Integer, List<Integer>> map = new TreeMap<>();
        for (int i = 0; i < n; i++) {
            if (map.containsKey(times[i][0])){
                map.get(times[i][0]).add(i);
            }else {
                List<Integer> list = new ArrayList<>();
                list.add(i);
                map.put(times[i][0], list);
            }
        }
        PriorityQueue<int[]> queue = new PriorityQueue<>(Comparator.comparingInt(o -> o[0]));
        PriorityQueue<Integer> sites = new PriorityQueue<>(Comparator.comparingInt(o -> o));
        for (int i = 0; i < n; i++) {
            sites.add(i);
        }
        for (int i = 0; i <= arrive; i++) {
            while (!queue.isEmpty() && queue.peek()[0] <= i){
                sites.add(queue.poll()[1]);
            }
            if (i == arrive){
                return sites.poll();
            }
            if (map.containsKey(i)){
                for (Integer index : map.get(i)) {
                    queue.add(new int[]{times[index][1], sites.poll()});
                }
            }
        }
        return 0;
    }
}
